package cn.ysym.tcsy;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.ysym.dao.DealerDao;
import cn.ysym.dao.SettingDao;
import cn.ysym.dao.ShippingOrderDao;
import cn.ysym.model.Dealer;
import cn.ysym.model.Setting;
import cn.ysym.model.ShippingOrder;
import cn.ysym.util.CommonUtil;
import cn.ysym.util.HttpUtil;
import cn.ysym.util.VibratorUtil;

public class OnlineShippingActivity extends AppCompatActivity {

    @BindView(R.id.lvData)
    ListView lvData;
    @BindView(R.id.etDealer)
    EditText etDealer;
    @BindView(R.id.lvDealer)
    ListView lvDealer;
    @BindView(R.id.lvShippingId)
    ListView lvShippingId;
    private boolean taskDoing = false;
    private ProgressBar progressBar;
    private SettingDao settingDao;
    private EditText etShippingId;
    private RadioGroup rgShippingType;
    private EditText etCode;
    private TextView tvResult;
    private Button bShippingFinish;
    private DealerDao dealerDao;
    private ShippingOrderDao shippingOrderDao;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_online_shipping);
        ButterKnife.bind(this); //绑定butterKnife插件
        setTitle("在线出库");

        progressBar = findViewById(R.id.progressBarOnline);
        settingDao = new SettingDao(this);
        dealerDao = new DealerDao(this);
        shippingOrderDao = new ShippingOrderDao(this);

        etShippingId = findViewById(R.id.etShippingId);
        rgShippingType = findViewById(R.id.rgShippingType);
        etCode = findViewById(R.id.etCode);
        tvResult = findViewById(R.id.tvResult);

        etDealer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    ArrayAdapter<String> tAdapter = new ArrayAdapter<String>(OnlineShippingActivity.this, R.layout.list_view);
                    List<Dealer> models = dealerDao.query("");
                    for (Dealer model : models) {
                        tAdapter.add(CommonUtil.formatStr(model.getDealerId() + " " + model.getDealerName()));
                    }
                    lvDealer.setAdapter(tAdapter);
                    lvDealer.setVisibility(View.VISIBLE);
                } else {
                    lvDealer.setVisibility(View.GONE);
                }
            }
        });

        etDealer.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                ArrayAdapter<String> tAdapter = new ArrayAdapter<>(OnlineShippingActivity.this, R.layout.list_view);
                List<Dealer> models = dealerDao.query(s.toString());
                for (Dealer model : models) {
                    tAdapter.add(CommonUtil.formatStr(model.getDealerId() + " " + model.getDealerName()));
                }
                lvDealer.setAdapter(tAdapter);
                lvDealer.setVisibility(View.VISIBLE);
            }
        });

        lvDealer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = parent.getAdapter().getItem(position).toString();
                etDealer.setText(text);
                lvDealer.setVisibility(View.GONE);
                etCode.requestFocus();
            }
        });

//        etShippingId.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean focused) {
//                if (focused) {
//                    taskDoing = true;
//                    progressBar.setVisibility(View.VISIBLE);
//                    GetShippingListTask task = new GetShippingListTask();
//                    task.execute((Void) null);
//                }
//            }
//        });
//
//        etShippingId.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                ArrayAdapter<String> orderAdapter = new ArrayAdapter<>(OnlineShippingActivity.this, R.layout.list_view);
//                List<ShippingOrder> ps = shippingOrderDao.query(s.toString());
//                for (ShippingOrder p : ps) {
//                    orderAdapter.add(CommonUtil.formatStr(p.getOrderNo()));
//                }
//                lvShippingId.setAdapter(orderAdapter);
//                lvShippingId.setVisibility(View.VISIBLE);
//            }
//        });

//        lvShippingId.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                String text = parent.getAdapter().getItem(position).toString();
//                text = text.trim().replace("\n", "");
//                etShippingId.setText(text);
//                lvShippingId.setVisibility(View.GONE);
//                etDealer.requestFocus();
//                //获取选中发货单号详情
//                taskDoing = true;
//                progressBar.setVisibility(View.VISIBLE);
//                GetShippingDetailTask task = new GetShippingDetailTask(text);
//                task.execute((Void) null);
//            }
//        });

        etCode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (taskDoing) {
                        Toast.makeText(getApplicationContext(), "正在处理，请稍后", Toast.LENGTH_SHORT).show();
                    } else {
                        String code = CommonUtil.cleanCode(etCode.getText().toString());
                        etCode.setText(code);

                        String shippingType = "1";
                        RadioButton rbChecked = findViewById(rgShippingType.getCheckedRadioButtonId());
                        if (!"出库".equals(rbChecked.getText())) shippingType = "4";

                        String shippingId = etShippingId.getText().toString().trim().replace("\n", "");
                        if (shippingType.equals("1") && shippingId.trim().length() < 1) {
                            VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                            CommonUtil.playSound(OnlineShippingActivity.this);
                            Toast.makeText(getApplicationContext(), "发货单号必须输入", Toast.LENGTH_SHORT).show();
                            etCode.setText("");
                            return false;
                        }

                        String dealerId = etDealer.getText().toString();
                        int tIndex = dealerId.indexOf(" ");
                        if (tIndex > 0) dealerId = dealerId.substring(0, tIndex);

                        taskDoing = true;
                        progressBar.setVisibility(View.VISIBLE);
                        UpDataTask upDataTask = new UpDataTask(shippingType, shippingId, code,dealerId);
                        upDataTask.execute((Void) null);
                    }
                }
                return false;
            }
        });

        bShippingFinish = findViewById(R.id.bShippingFinish);
        bShippingFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //弹出退出确认框
                new AlertDialog.Builder(OnlineShippingActivity.this)
                        .setTitle("系统提示")
                        .setMessage("确认出库完成？")
                        .setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                taskDoing = true;
                                progressBar.setVisibility(View.VISIBLE);
                                String dealerId = etDealer.getText().toString();
                                String shippingId = etShippingId.getText().toString().trim().replace("\n", "");
                                int tIndex = dealerId.indexOf(" ");
                                if (tIndex > 0) dealerId = dealerId.substring(0, tIndex);
                                ShippingFinishTask task = new ShippingFinishTask(dealerId,shippingId);
                                task.execute((Void) null);
                                String code = CommonUtil.cleanCode(etCode.getText().toString());
                                String shippingType = "1";
                                GetShippingDetailTask task1 = new GetShippingDetailTask(shippingType,shippingId,code,dealerId);
                                task1.execute((Void) null);
                                etDealer.setText("");
                                etDealer.requestFocus();
                                etShippingId.setText("");
                                etShippingId.requestFocus();
                            }
                        }).setNegativeButton("取消", null).show();
            }
        });
    }

    /**
     * 监听Back键按下事件
     */
    @Override
    public void onBackPressed() {
        //弹出退出确认框
        new AlertDialog.Builder(OnlineShippingActivity.this)
                .setTitle("系统提示")
                .setMessage("是否确认退出？")
                .setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //退出app
                        finish();
                    }
                }).setNegativeButton("取消", null).show();
    }
    public class GetShippingListTask extends AsyncTask<Void, Void, String> {
        private String message = "对不起，服务异常！";

        @Override
        protected String doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");
                req.put("version", CommonUtil.getSoftVersion());
                req.put("account", userName.getSettingValue());
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = HttpUtil.postJson("getShippingList.sdo", req.toString());
                return retStr;
            } catch (Exception e) {
                message = e.getMessage();
            }

            return null;
        }

        @Override
        protected void onPostExecute(final String retStr) {
            taskDoing = false;
            progressBar.setVisibility(View.GONE);

            if (retStr != null) {
                try {
                    JSONObject retJson = new JSONObject(retStr);
                    tvResult.setText("");
                    JSONArray data = retJson.getJSONArray("data");
                    int length = data.length();
                    ArrayAdapter<String> tAdapter = new ArrayAdapter<>(OnlineShippingActivity.this, R.layout.list_view);
                    shippingOrderDao.clearAll();
                    for (int i = 0; i < length; i++) {//遍历JSONArray
                        tAdapter.add((String) data.get(i));
                        ShippingOrder shippingOrder = new ShippingOrder();
                        shippingOrder.setOrderNo((String) data.get(i));
                        shippingOrderDao.insert(shippingOrder);
                    }
                    lvShippingId.setAdapter(tAdapter);
                    lvShippingId.setVisibility(View.VISIBLE);

                    if (retJson.getInt("status") != 200) {
                        CommonUtil.playSound(OnlineShippingActivity.this);
                        message = retJson.getString("message");
                        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                        tvResult.setText(message);
                    }

                } catch (JSONException e) {
                    message = e.getMessage();
                }
            } else {
                VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
            }
        }

    }

    public class GetShippingDetailTask extends AsyncTask<Void, Void, String> {
        private String shippingId;
        private String code;
        private String dealerId;
        private String shippingType;
        private String message = "对不起，服务异常！";

        public GetShippingDetailTask(String shippingType, String shippingId, String code, String dealerId) {
            this.shippingType = shippingType;
            this.shippingId = shippingId;
            this.code = code;
            this.dealerId = dealerId;
        }

        @Override
        protected String doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");
                req.put("version", CommonUtil.getSoftVersion());
                req.put("account", userName.getSettingValue());
                req.put("type", shippingType);
                req.put("shippingId", shippingId);
                req.put("code", code);
                req.put("dealerId", dealerId);
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = HttpUtil.postJson("getShippingDetail.sdo", req.toString());
                return retStr;
            } catch (Exception e) {
                message = e.getMessage();
            }

            return null;
        }

@Override
protected void onPostExecute(final String retStr) {
    taskDoing = false;
    progressBar.setVisibility(View.GONE);

    if (retStr != null) {
        try {
            JSONObject retJson = new JSONObject(retStr);
            JSONArray data = retJson.getJSONArray("data");
            List<HashMap<String, Object>> listData = new ArrayList<>();
            for (int i = 0; i < data.length(); i++) {
                JSONObject item = data.getJSONObject(i);
                HashMap<String, Object> oneData = new HashMap<>();
                String productName = item.getString("productName");
                String bigNum = item.getString("bigNumber");
                String midNum = item.getString("middleNumber");
                String sanNum = item.getString("sanNumber");
                oneData.put("productName", productName);
                oneData.put("bigNumber", bigNum);
                oneData.put("middleNumber", midNum);
                oneData.put("sanNumber", sanNum);
                listData.add(oneData);
            }

            SimpleAdapter adapter = new SimpleAdapter(OnlineShippingActivity.this, listData, R.layout.shipping_data_item,
                    new String[]{"productName", "bigNumber", "middleNumber", "sanNumber"}, new int[]{R.id.tvProductId, R.id.tvProductName, R.id.tvSendNum, R.id.tvSentNum});
            lvData.setAdapter(adapter);

            if (retJson.getInt("status") != 200) {
                message = retJson.getString("message");
                VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                tvResult.setText(message);
            }

        } catch (JSONException e) {
            message = e.getMessage();
        }
    } else {
        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }
}
    }

    public class UpDataTask extends AsyncTask<Void, Void, String> {
        private String shippingType;
        private String shippingId;
        private String code;
        private String dealerId;
        private String message = "对不起，服务异常！";

        public UpDataTask(String shippingType, String shippingId, String code,  String dealerId) {
            this.shippingType = shippingType;
            this.shippingId = shippingId;
            this.code = code;
            this.dealerId = dealerId;
        }

        @Override
        protected String doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");
                req.put("version", CommonUtil.getSoftVersion());
                req.put("account", userName.getSettingValue());
                req.put("type", shippingType);
                req.put("shippingId", shippingId);
                req.put("code", code);
                req.put("dealerId", dealerId);
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = null;
                if("1".equals(shippingType)){
                    retStr = HttpUtil.postJson("upShippingTask.sdo", req.toString());
                }else if("4".equals(shippingType)){
                    retStr = HttpUtil.postJson("removeShippingTask.sdo",req.toString());
                }
                return retStr;
            } catch (Exception e) {
                message = e.getMessage();
            }

            return null;
        }

        @Override
        protected void onPostExecute(final String retStr) {
            taskDoing = false;
            progressBar.setVisibility(View.GONE);
            if (retStr != null) {
                try {
                    JSONObject retJson = new JSONObject(retStr);
                    tvResult.setText("");
                    if (retJson.getInt("result") == 1) {
                        //更新订单详情
                        taskDoing = true;
                        progressBar.setVisibility(View.VISIBLE);
                        GetShippingDetailTask task = new GetShippingDetailTask(shippingType, shippingId, code,dealerId);
                        task.execute((Void) null);
                        message = retJson.getString("message");
                        tvResult.setText(message);
                    } else {
                        CommonUtil.playSound(OnlineShippingActivity.this);
                        message = retJson.getString("message");
                        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                        tvResult.setText(message);
                    }
                } catch (JSONException e) {
                    message = e.getMessage();
                }
                etCode.setText("");
                etCode.requestFocus();
            } else {
                CommonUtil.playSound(OnlineShippingActivity.this);
                tvResult.setText(message);
                VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
            }
        }

    }

    public class ShippingFinishTask extends AsyncTask<Void, Void, String> {
        private String dealerId;
        private String shippingId;
        private String message = "对不起，服务异常！";

        public ShippingFinishTask(String dealerId,String shippingId) {
            this.dealerId = dealerId;
            this.shippingId = shippingId;
        }

        @Override
        protected String doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");
                req.put("version", CommonUtil.getSoftVersion());
                req.put("account", userName.getSettingValue());
                req.put("dealerId",dealerId);
                req.put("shippingId",shippingId);
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = HttpUtil.postJson("upShippingFinish.sdo", req.toString());
                return retStr;
            } catch (Exception e) {
                message = e.getMessage();
            }

            return null;
        }

        @Override
        protected void onPostExecute(final String retStr) {
            taskDoing = false;
            progressBar.setVisibility(View.GONE);

            if (retStr != null) {
                try {
                    JSONObject retJson = new JSONObject(retStr);
                    if (retJson.getInt("status") == 200) {
                        Toast.makeText(getApplicationContext(), "成功", Toast.LENGTH_SHORT).show();
                        tvResult.setText("成功");
                    } else {
                        CommonUtil.playSound(OnlineShippingActivity.this);
                        message = retJson.getString("message");
                        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                        tvResult.setText(message);
                    }
                } catch (JSONException e) {
                    message = e.getMessage();
                }

            } else {
                CommonUtil.playSound(OnlineShippingActivity.this);
                tvResult.setText(message);
            }
        }

    }

}
